<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/auth.php';
require_once '../includes/config_manager.php';

// 检查权限
$auth = getAuth();
$auth->requirePermission('super_admin');

// 获取当前用户信息
$currentUser = $auth->getCurrentUser();

// 初始化数据库和配置管理器
$database = getDatabaseConnection();
$configManager = new ConfigManager($database);

// 处理表单提交
$message = '';
$messageType = '';

if ($_POST) {
    $action = $_POST['action'] ?? '';
    
    try {
        switch ($action) {
            case 'save_work_time':
                $workTimeConfig = [
                    'work_start_time' => $_POST['work_start_time'],
                    'work_end_time' => $_POST['work_end_time'],
                    'lunch_start_time' => $_POST['lunch_start_time'],
                    'lunch_end_time' => $_POST['lunch_end_time'],
                    'work_days' => implode(',', $_POST['work_days'] ?? []),
                    'overtime_rate' => $_POST['overtime_rate'],
                    'late_threshold' => $_POST['late_threshold'],
                    'early_leave_threshold' => $_POST['early_leave_threshold']
                ];
                
                if ($configManager->setWorkTimeConfig($workTimeConfig)) {
                    $message = '工作时间配置保存成功';
                    $messageType = 'success';
                } else {
                    throw new Exception('保存工作时间配置失败');
                }
                break;
                
            case 'save_system_config':
                $configData = [
                    'system_name' => $_POST['system_name'],
                    'company_name' => $_POST['company_name'],
                    'admin_email' => $_POST['admin_email'],
                    'auto_backup' => $_POST['auto_backup'],
                    'backup_interval' => $_POST['backup_interval']
                ];
                
                $success = true;
                foreach ($configData as $key => $value) {
                    if (!$configManager->setConfig($key, $value)) {
                        $success = false;
                    }
                }
                
                if ($success) {
                    $message = '系统配置保存成功';
                    $messageType = 'success';
                } else {
                    throw new Exception('保存系统配置失败');
                }
                break;
                
            case 'add_config':
                $key = $_POST['config_key'];
                $value = $_POST['config_value'];
                $description = $_POST['description'];
                
                if ($configManager->setConfig($key, $value, $description)) {
                    $message = '配置项添加成功';
                    $messageType = 'success';
                } else {
                    throw new Exception('添加配置项失败');
                }
                break;
                
            case 'update_config':
                $key = $_POST['config_key'];
                $value = $_POST['config_value'];
                $description = $_POST['description'];
                
                if ($configManager->setConfig($key, $value, $description)) {
                    $message = '配置项更新成功';
                    $messageType = 'success';
                } else {
                    throw new Exception('更新配置项失败');
                }
                break;
                
            case 'delete_config':
                $key = $_POST['config_key'];
                if ($configManager->deleteConfig($key)) {
                    $message = '配置项删除成功';
                    $messageType = 'success';
                } else {
                    throw new Exception('删除配置项失败');
                }
                break;
                
            case 'initialize_defaults':
                if ($configManager->initializeDefaultConfigs()) {
                    $message = '默认配置初始化成功';
                    $messageType = 'success';
                } else {
                    throw new Exception('初始化默认配置失败');
                }
                break;
        }
    } catch (Exception $e) {
        $message = $e->getMessage();
        $messageType = 'danger';
    }
}

// 获取配置数据
$workTimeConfig = $configManager->getWorkTimeConfig();
$allConfigs = $configManager->getAllConfigs();
$systemInfo = $configManager->getSystemInfo();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统配置 - 考勤管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- 侧边栏 -->
    <?php include_once '../includes/sidebar.php'; ?>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand navbar-custom mb-4">
            <div class="container-fluid">
                <div class="navbar-nav me-auto">
                    <span class="navbar-text">
                        <i class="fas fa-cog me-2"></i>系统配置
                    </span>
                </div>
                <div class="navbar-nav">
                    <span class="navbar-text me-3">
                        <i class="fas fa-user me-2"></i>
                        <?php echo htmlspecialchars($currentUser['full_name']); ?>
                    </span>
                    <a href="../user/profile.php" class="nav-link">
                        <i class="fas fa-cog"></i> 个人设置
                    </a>
                </div>
            </div>
        </nav>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                <i class="fas fa-<?php echo $messageType === 'success' ? 'check' : 'exclamation-triangle'; ?> me-2"></i>
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- 系统信息卡片 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $systemInfo['total_users']; ?></h4>
                        <p class="mb-0">总用户数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $systemInfo['total_records']; ?></h4>
                        <p class="mb-0">考勤记录</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $systemInfo['php_version']; ?></h4>
                        <p class="mb-0">PHP版本</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body text-center">
                        <h4><?php echo substr($systemInfo['mysql_version'], 0, 6); ?></h4>
                        <p class="mb-0">MySQL版本</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 配置选项卡 -->
        <ul class="nav nav-tabs mb-4" id="configTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="work-time-tab" data-bs-toggle="tab" data-bs-target="#work-time" type="button" role="tab">
                    <i class="fas fa-clock me-2"></i>工作时间配置
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="system-tab" data-bs-toggle="tab" data-bs-target="#system" type="button" role="tab">
                    <i class="fas fa-cog me-2"></i>系统设置
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="all-configs-tab" data-bs-toggle="tab" data-bs-target="#all-configs" type="button" role="tab">
                    <i class="fas fa-list me-2"></i>所有配置项
                </button>
            </li>
        </ul>

        <div class="tab-content" id="configTabsContent">
            <!-- 工作时间配置 -->
            <div class="tab-pane fade show active" id="work-time" role="tabpanel">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-clock me-2"></i>工作时间配置
                        </h5>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <input type="hidden" name="action" value="save_work_time">
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">上班时间</label>
                                        <input type="time" name="work_start_time" class="form-control" 
                                               value="<?php echo htmlspecialchars($workTimeConfig['work_start_time']); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">下班时间</label>
                                        <input type="time" name="work_end_time" class="form-control" 
                                               value="<?php echo htmlspecialchars($workTimeConfig['work_end_time']); ?>" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">午休开始时间</label>
                                        <input type="time" name="lunch_start_time" class="form-control" 
                                               value="<?php echo htmlspecialchars($workTimeConfig['lunch_start_time']); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">午休结束时间</label>
                                        <input type="time" name="lunch_end_time" class="form-control" 
                                               value="<?php echo htmlspecialchars($workTimeConfig['lunch_end_time']); ?>" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">工作日</label>
                                <div class="form-check">
                                    <?php
                                    $workDays = explode(',', $workTimeConfig['work_days']);
                                    $weekDays = [
                                        1 => '周一',
                                        2 => '周二', 
                                        3 => '周三',
                                        4 => '周四',
                                        5 => '周五',
                                        6 => '周六',
                                        7 => '周日'
                                    ];
                                    foreach ($weekDays as $dayNum => $dayName): ?>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="checkbox" name="work_days[]" 
                                                   value="<?php echo $dayNum; ?>" 
                                                   id="day<?php echo $dayNum; ?>"
                                                   <?php echo in_array($dayNum, $workDays) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="day<?php echo $dayNum; ?>">
                                                <?php echo $dayName; ?>
                                            </label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label class="form-label">加班工资倍数</label>
                                        <input type="number" name="overtime_rate" class="form-control" step="0.1" min="1" max="3"
                                               value="<?php echo htmlspecialchars($workTimeConfig['overtime_rate']); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label class="form-label">迟到阈值（分钟）</label>
                                        <input type="number" name="late_threshold" class="form-control" min="1" max="60"
                                               value="<?php echo htmlspecialchars($workTimeConfig['late_threshold']); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label class="form-label">早退阈值（分钟）</label>
                                        <input type="number" name="early_leave_threshold" class="form-control" min="1" max="60"
                                               value="<?php echo htmlspecialchars($workTimeConfig['early_leave_threshold']); ?>" required>
                                    </div>
                                </div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>保存工作时间配置
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- 系统设置 -->
            <div class="tab-pane fade" id="system" role="tabpanel">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-cog me-2"></i>系统设置
                        </h5>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <input type="hidden" name="action" value="save_system_config">
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">系统名称</label>
                                        <input type="text" name="system_name" class="form-control" 
                                               value="<?php echo htmlspecialchars($configManager->getConfig('system_name') ?? '考勤管理系统'); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">公司名称</label>
                                        <input type="text" name="company_name" class="form-control" 
                                               value="<?php echo htmlspecialchars($configManager->getConfig('company_name') ?? '示例公司'); ?>" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">管理员邮箱</label>
                                <input type="email" name="admin_email" class="form-control" 
                                       value="<?php echo htmlspecialchars($configManager->getConfig('admin_email') ?? 'admin@example.com'); ?>" required>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">自动备份</label>
                                        <select name="auto_backup" class="form-select">
                                            <option value="1" <?php echo ($configManager->getConfig('auto_backup') ?? '1') == '1' ? 'selected' : ''; ?>>启用</option>
                                            <option value="0" <?php echo ($configManager->getConfig('auto_backup') ?? '1') == '0' ? 'selected' : ''; ?>>禁用</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">备份间隔（天）</label>
                                        <input type="number" name="backup_interval" class="form-control" min="1" max="30"
                                               value="<?php echo htmlspecialchars($configManager->getConfig('backup_interval') ?? '7'); ?>" required>
                                    </div>
                                </div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>保存系统设置
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- 所有配置项 -->
            <div class="tab-pane fade" id="all-configs" role="tabpanel">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-list me-2"></i>所有配置项
                        </h5>
                        <div>
                            <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#addConfigModal">
                                <i class="fas fa-plus me-2"></i>添加配置项
                            </button>
                            <button class="btn btn-warning btn-sm" onclick="initializeDefaults()">
                                <i class="fas fa-sync me-2"></i>初始化默认配置
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if (empty($allConfigs)): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-cog fa-4x mb-3"></i>
                                <h4>暂无配置项</h4>
                                <p>点击"添加配置项"按钮创建第一个配置项</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>配置键</th>
                                            <th>配置值</th>
                                            <th>描述</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($allConfigs as $config): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($config['config_key']); ?></td>
                                                <td><?php echo htmlspecialchars($config['config_value']); ?></td>
                                                <td><?php echo htmlspecialchars($config['description']); ?></td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <button class="btn btn-outline-primary" 
                                                                data-bs-toggle="modal" 
                                                                data-bs-target="#editConfigModal"
                                                                onclick="loadConfigData('<?php echo htmlspecialchars($config['config_key']); ?>', '<?php echo htmlspecialchars($config['config_value']); ?>', '<?php echo htmlspecialchars($config['description']); ?>')">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                        <button class="btn btn-outline-danger" 
                                                                onclick="confirmDeleteConfig('<?php echo htmlspecialchars($config['config_key']); ?>')">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加配置项模态框 -->
    <div class="modal fade" id="addConfigModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="post">
                    <div class="modal-header">
                        <h5 class="modal-title">添加配置项</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_config">
                        <div class="mb-3">
                            <label class="form-label">配置键 *</label>
                            <input type="text" name="config_key" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">配置值 *</label>
                            <input type="text" name="config_value" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">描述</label>
                            <textarea name="description" class="form-control" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">添加配置项</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 编辑配置项模态框 -->
    <div class="modal fade" id="editConfigModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="post">
                    <div class="modal-header">
                        <h5 class="modal-title">编辑配置项</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="update_config">
                        <input type="hidden" name="config_key" id="edit_config_key">
                        <div class="mb-3">
                            <label class="form-label">配置键</label>
                            <input type="text" id="edit_config_key_display" class="form-control" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">配置值 *</label>
                            <input type="text" name="config_value" id="edit_config_value" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">描述</label>
                            <textarea name="description" id="edit_description" class="form-control" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">保存修改</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 删除配置项表单 -->
    <form id="deleteConfigForm" method="post" style="display: none;">
        <input type="hidden" name="action" value="delete_config">
        <input type="hidden" name="config_key" id="delete_config_key">
    </form>

    <!-- 初始化默认配置表单 -->
    <form id="initializeDefaultsForm" method="post" style="display: none;">
        <input type="hidden" name="action" value="initialize_defaults">
    </form>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 加载配置数据到编辑模态框
        function loadConfigData(key, value, description) {
            document.getElementById('edit_config_key').value = key;
            document.getElementById('edit_config_key_display').value = key;
            document.getElementById('edit_config_value').value = value;
            document.getElementById('edit_description').value = description || '';
        }

        // 确认删除配置项
        function confirmDeleteConfig(key) {
            if (confirm(`确定要删除配置项 "${key}" 吗？此操作不可逆！`)) {
                document.getElementById('delete_config_key').value = key;
                document.getElementById('deleteConfigForm').submit();
            }
        }

        // 初始化默认配置
        function initializeDefaults() {
            if (confirm('确定要初始化默认配置吗？这将覆盖现有的配置项！')) {
                document.getElementById('initializeDefaultsForm').submit();
            }
        }

        // 页面加载完成后的一些初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 自动激活第一个选项卡
            const firstTab = document.querySelector('#configTabs .nav-link');
            if (firstTab) {
                firstTab.click();
            }
        });
    </script>
</body>
</html>
